//
//  CategoryViewController.swift
//  WangPu
//
//  Created by xiaozhi on 15/9/15.
//  Copyright (c) 2015年 zhixiao. All rights reserved.
//

import UIKit

class CategoryViewController: BaseViewController {
    var leftTable:UITableView!
    var rightTable:UITableView!
    var selectIndex:NSIndexPath?
    var searchBar:UISearchBar!
    var bannerImage:XZImageView!
    var leftTableDataSource:NSMutableArray!
    var rightTableDataSource:[NSDictionary] = []
    var dataPullSuccess:Bool = false
    var selectIndexOfLeftTable:NSIndexPath =  NSIndexPath(forRow: 0, inSection: 0)
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "分类"
        // Do any additional setup after loading the view.
        self.setupTopView()
        self.createLeftTableView()
        self.createRightTableView()
        self.queryTopCategory("防晒",offset:0, length: 9)
//        let timer:dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(2.0*Double(NSEC_PER_SEC)))
//        dispatch_after(timer, dispatch_get_main_queue(), {
//            let ctl = GoodsDetailViewController()
//            ctl.hidesBottomBarWhenPushed = true
//            self.navigationController?.pushViewController(ctl, animated: true)
//        })
    }
    func showInfo(){
        let ctl = MessageViewController()
        self.navigationController?.pushViewController(ctl, animated: true)
    }
    func setupTopView(){
        //237,63,88
        let topView = UIView(frame: CGRectMake(0, 0, view.bounds.size.width, topViewHeight))
        topView.backgroundColor = commonRedColor
        view.addSubview(topView)
        
        searchBar = UISearchBar(frame: CGRectMake(10, 22, view.bounds.size.width-10-40, 40))
        searchBar.searchBarStyle = UISearchBarStyle.Prominent
        searchBar.placeholder = "女神新装"
        searchBar.delegate = self
        if let aview = searchBar.subviews[0] as? UIView{
            if aview.subviews.count>0{
                aview.subviews[0].removeFromSuperview()
            }
        }
        topView.addSubview(searchBar)
        
        let messageBtn = MyButton(frame: CGRectMake(0, 0, 40, 40))
        messageBtn.imageSize = CGSizeMake(16, 16)
        messageBtn.center = CGPointMake(topView.bounds.size.width - messageBtn.frame.size.width/2.0-3, searchBar.center.y)
        //        messageBtn.alwaysUnhightlighted = false
        messageBtn.setTitle("消息", forState: UIControlState.Normal)
        messageBtn.titleLabel?.font = UIFont.boldSystemFontOfSize(11)
        messageBtn.titleLabel?.textAlignment = NSTextAlignment.Center
        messageBtn.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
        messageBtn.setImage(UIImage(named:"chat-"), forState: UIControlState.Normal)
        messageBtn.addTarget(self, action: "showInfo", forControlEvents: UIControlEvents.TouchUpInside)
        messageBtn.imageView?.contentMode = UIViewContentMode.ScaleAspectFit
        topView.addSubview(messageBtn)
    }
    func createLeftTableView(){
        leftTableDataSource = NSMutableArray()
//        leftTableDataSource.addObjectsFromArray(["热门品牌","食品/保健","美妆个护","母婴用品","服饰鞋包","生活数码"])
        leftTable = UITableView(frame: CGRectMake(0, topViewHeight, 100, view.bounds.size.height-topViewHeight-tabbarHeight), style: UITableViewStyle.Plain)
        leftTable.separatorStyle = UITableViewCellSeparatorStyle.None
        leftTable.showsHorizontalScrollIndicator = false
        leftTable.showsVerticalScrollIndicator = false
        leftTable.dataSource = self
        leftTable.delegate = self
        let nib = UINib(nibName:"CategoryGoodsCell", bundle: nil)
        leftTable.registerNib(nib, forCellReuseIdentifier:"CategoryGoodsCellID")
        view.addSubview(leftTable)
    }
    func createRightTableView(){
        
        rightTable = UITableView(frame: CGRectMake(CGRectGetMaxX(leftTable.frame)+10, topViewHeight, view.bounds.size.width-leftTable.frame.size.width - 20, view.bounds.size.height-topViewHeight-tabbarHeight), style: UITableViewStyle.Plain)
        rightTable.separatorStyle = UITableViewCellSeparatorStyle.None
        rightTable.backgroundColor = UIColor.clearColor()
        rightTable.showsHorizontalScrollIndicator = false
        rightTable.showsVerticalScrollIndicator = false
        rightTable.dataSource = self
        rightTable.delegate = self
        let nib = UINib(nibName:"ShopListCell", bundle: nil)
        rightTable.registerNib(nib, forCellReuseIdentifier:"ShopCell")
        bannerImage = XZImageView(frame: CGRectMake(0, 0, rightTable.bounds.size.width, 120))
        bannerImage.backgroundColor = UIColor.whiteColor()
        bannerImage.layer.cornerRadius = 5.0
        bannerImage.clipsToBounds = true
        bannerImage.contentMode = UIViewContentMode.ScaleAspectFill
        rightTable.tableHeaderView = bannerImage;
        view.addSubview(rightTable)
    }

    func queryTopCategory(category:String!,offset:Int,length:Int)->Void{
        let request = NetWorkHelper()
        let parameters = NSMutableDictionary()
        parameters.setObject("getcategory", forKey: "action")
//        parameters.setObject(NSNumber(integer: offset),forKey: "c")
//        parameters.setObject(NSNumber(integer:length), forKey: "s")
        request.requestStart("/category/getcategory", parameters: parameters,compeleteHandle:{ (data, response, error)  in
            dispatch_async(dispatch_get_main_queue()){
                self.hiddenProcessView()
            }
            if error == nil{
                var dic:NSDictionary?
                do {
                    dic = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as? NSDictionary
                } catch let error as NSError {
                    print(error)
                    dispatch_async(dispatch_get_main_queue()){
                        self.showTips("服务器数据异常")
                    }
                    return
                }
                if (dic?["result"])! as! String == "0"{
                    self.dataPullSuccess = true
                    if let array = dic?["data"] as? NSArray{
                        self.leftTableDataSource.addObjectsFromArray(array as [AnyObject])
                    }
                    dispatch_async(dispatch_get_main_queue()){
                        self.leftTable.reloadData()
                        
                        self.tableView(self.leftTable, didSelectRowAtIndexPath: self.selectIndexOfLeftTable)
                    }
                }
                

            }
        })
        self.showProcess("加载中...")
    }
    func selectMenuWithIndexPath(indexpath:NSIndexPath){
        if self.dataPullSuccess{
            self.tableView(self.leftTable, didSelectRowAtIndexPath:indexpath)
        }
    }
    func querySubCategory(category:String!)->Void{
        let request = NetWorkHelper()
        let parameters = NSMutableDictionary()
        parameters.setObject(category, forKey: "categoryName")
        //        parameters.setObject(NSNumber(integer: offset),forKey: "c")
        //        parameters.setObject(NSNumber(integer:length), forKey: "s")
        request.requestStart("/category/getsubCategory", parameters: parameters,compeleteHandle:{ (data, response, error)  in
            dispatch_async(dispatch_get_main_queue()){
                self.hiddenProcessView()
            }
            if error == nil{
                var dic:NSDictionary?
                do {
                    dic = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as? NSDictionary
                } catch let error as NSError {
                    print(error)
                }
                if let contenDic = dic?["data"] as? NSDictionary{
                    let url = contenDic["image"] as? String
                    print(url)
                    dispatch_async(dispatch_get_main_queue()){
                        self.bannerImage.setImageWithUrl(url!, defaultImage: nil)
                    }
                    if let array = contenDic["subcategory"] as? NSArray{
                        self.rightTableDataSource = array as! [NSDictionary]
                    }
                }
                dispatch_async(dispatch_get_main_queue()){
                    self.rightTable.reloadData()
                }
            }
        })
        self.showProcess("加载中...")
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.navigationBarHidden = true
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
extension CategoryViewController:UITableViewDelegate,UITableViewDataSource{
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        if tableView == leftTable{
            return  self.leftTableDataSource.count
        }
        else{
            if rightTableDataSource.count%2 == 0{
                return rightTableDataSource.count/2
            }
            else{
                return rightTableDataSource.count/2 + 1
            }
        }
    }
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) ->UITableViewCell{
        if tableView == leftTable{
            let cell = tableView.dequeueReusableCellWithIdentifier("CategoryGoodsCellID", forIndexPath: indexPath) as! CategoryGoodsCell
            if let select = selectIndex{
                if select==indexPath{
                    cell.showHight(false)
                }
                else{
                    cell.showUnhight(false)
                }
            }
            if let dic = leftTableDataSource[indexPath.row] as? NSDictionary{
                cell.typeName.text = dic["name"] as? String
            }
            return cell;
        }
        else{
            let cell = tableView.dequeueReusableCellWithIdentifier("ShopCell", forIndexPath: indexPath) as! ShopListCell
            //        cell.wineImageView.image = imageArray[indexPath.row].0
            cell.indexPath = indexPath
            var obj1,obj2:NSDictionary?
            obj1 = rightTableDataSource[indexPath.row*2]
            if indexPath.row*2+1 < rightTableDataSource.count{
                obj2 = rightTableDataSource[indexPath.row*2+1]
            }
            cell.imageView1.setImageWithUrl(obj1!["subimageurl"]! as! String, defaultImage:nil)
            cell.lbl00.text = obj1?["name"] as? String
            if obj2 == nil{
                cell.cell2.hidden = true
            }
            else{
                cell.imageView2.setImageWithUrl(obj2!["subimageurl"]! as! String, defaultImage:nil)
                cell.lbl10.text = obj2?["name"] as? String
            }
            
            cell.btnHandle = {[weak self] indexPath,buttonIndex in
                print("第\(indexPath!.row)个cell,第\(buttonIndex)个按钮")
//                self?.selectObj = self?.rightMenuSource[indexPath!.row*2+buttonIndex]
                let ctl = GoodsDisplayViewController()
                if let dic = self?.rightTableDataSource[indexPath!.row]{
                    ctl.categoryName = dic["name"] as? String
                }
                ctl.hidesBottomBarWhenPushed = true
                self?.navigationController?.pushViewController(ctl, animated: true)
            }
            return cell;
        }
    }
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat{
        if tableView == leftTable{
            if UIScreen.mainScreen().bounds.size.width>320{
                return 50
            }
            return 40
        }
        else{
            return 180
        }
    }
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
        searchBar.resignFirstResponder()
        if tableView == leftTable{
            if let index = selectIndex{
                if let aselectCell = tableView.cellForRowAtIndexPath(index) as? CategoryGoodsCell{
                    aselectCell.showUnhight(true)
                    //                    UIView.animateWithDuration(0.2, delay: 0.0, options: UIViewAnimationOptions.CurveEaseOut, animations: {aselectCell.transform = CGAffineTransformIdentity}, completion:nil)
                }
            }
            
            if let cell = tableView.cellForRowAtIndexPath(indexPath) as? CategoryGoodsCell{
                cell.showHight(true)
                self.selectIndex = indexPath
                //                UIView.animateWithDuration(0.2, delay: 0.0, options: UIViewAnimationOptions.CurveEaseOut, animations: {cell.transform = CGAffineTransformMakeScale(1.1, 1.1)}, completion: {finished in self.selectIndex = indexPath})
            }
            rightTableDataSource.removeAll(keepCapacity: false)
            if let dic = leftTableDataSource[indexPath.row] as? NSDictionary{
                bannerImage.image = nil
                 self.querySubCategory(dic["name"] as! String)
            }
           
        }
        else{

        }
    }
    func scrollViewDidScroll(scrollView: UIScrollView){
        searchBar.resignFirstResponder()
    }
}
extension CategoryViewController:UISearchBarDelegate{
    func searchBarShouldBeginEditing(searchBar: UISearchBar) -> Bool{
        searchBar.resignFirstResponder()
        let ctl = SearchViewController()
        self.navigationController?.pushViewController(ctl, animated: true)
        return false
    }
}